// MFCSocketDlg_Client.cpp : implementation file
//

#include "stdafx.h"
#include "MFCSocket_Client.h"
#include "MFCSocketDlg_Client.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// CMFCSocketDlg_Client dialog
static CString Int2String(int n)
{
	char NUM[] = {'0','1','2','3','4','5','6','7','8','9'};
	//bool isNegative = false;
	int index = 0;
	char res[256];
	if(n < 0)
	{
		index = 1;
		//isNegative = true;
		n = -n;
		res[0] = '-';
	}

	while(n>0)
	{
		res[index] = NUM[n%10];
		n /= 10;
		index++;
	}
	int k = 0;
	if(res[0] == '-')
	{
		k=1;
	}
	for(int i=k; i<(index-k)/2+k; i++)
	{
		char tmp = res[i];
		res[i] = res[index-i-1+k];
		res[index-i-1+k] = tmp;
	}
	res[index] = '\0';
	CString s(res);
	return s;
}

static int DigitalCounter(int n)
{
	if(n<0)
		n=-n;
	int k=0;
	while(n>0)
	{
		n/=10;
		k++;
	}
	return k;
}

static int GetRandomNumber(int start, int end, int m);

CMFCSocketDlg_Client::CMFCSocketDlg_Client(CWnd* pParent /*=NULL*/)
	: CDialog(CMFCSocketDlg_Client::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CMFCSocketDlg_Client::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT_MESSAGE, sMsg);
}

BEGIN_MESSAGE_MAP(CMFCSocketDlg_Client, CDialog)
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDOK, &CMFCSocketDlg_Client::OnBnClickedOk)
	ON_BN_CLICKED(IDC_BTN_CONNECT, &CMFCSocketDlg_Client::OnBnClickedBtnConnect)
	ON_BN_CLICKED(IDC_BTN_SEND, &CMFCSocketDlg_Client::OnBnClickedBtnSend)
	ON_BN_CLICKED(IDC_BTN_STOP, &CMFCSocketDlg_Client::OnBnClickedBtnStop)
END_MESSAGE_MAP()


// CMFCSocketDlg_Client message handlers

BOOL CMFCSocketDlg_Client::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	m_ipAddress = L"127.0.0.1";
	m_port = 2000;
	GetDlgItem(IDC_BTN_CONNECT)->EnableWindow(true);
	GetDlgItem(IDC_BTN_SEND)->EnableWindow(false);
	GetDlgItem(IDC_BTN_STOP)->EnableWindow(false);

	m_socket.hwnd=this->GetSafeHwnd();
	
	m_clientID = GetRandomNumber(0, 10000, 111);
	//m_clientID = GetDlgCtrlID();
	//m_clientID = (int)this;

	char str[256];
	sprintf(str, "Client ID: %d", m_clientID);
	CString s(str);
	SetWindowText(s);

	sMsg = _T("");

	//((CMFCSocketDlg_Client*)m_socket.pDlg) = this;
	return TRUE;  // return TRUE  unless you set the focus to a control
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CMFCSocketDlg_Client::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CMFCSocketDlg_Client::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}


void CMFCSocketDlg_Client::OnBnClickedOk()
{
	// TODO: Add your control notification handler code here
	OnOK();
}

//////////////////////////////////////////////////////////////////////////
static int GetRandomNumber(int start, int end, int m = 1)
{
	int seed = ((start + end)*m*time(0) % 11013) + time(0);
	if(seed < 0)
		seed = -seed;
	srand(seed);
	srand(rand());
	return (rand() % (end - start) + start);
}
void CMFCSocketDlg_Client::SocketConnectServer()
{
	OutputDebugString(_T("[Client Dlg]: connect to server"));
	UpdateData(TRUE);
	if( AfxSocketInit() == FALSE)
	{ 
		AfxMessageBox(_T("Failed to Initialize Sockets")); 
		return; 
	}

	/*if(m_Client.Create()==FALSE)*/
	if(m_socket.Create() == FALSE)
	{
		MessageBox(_T("Failed to Create Socket"));
		return;

	}
	/*if(m_Client.Connect(m_sIPAddress,1001)==FALSE)*/
	if(m_socket.Connect(m_ipAddress, m_port) == FALSE)
	{
		MessageBox(_T("Failed to Connect"));
		m_socket.Close();
		return;

	}
	sprintf(szBuff, "%d%d%s", DigitalCounter(m_clientID), m_clientID, "^^^");
	m_socket.Send(szBuff, sizeof(szBuff));
	GetDlgItem(IDC_BTN_CONNECT)->EnableWindow(false);
	GetDlgItem(IDC_BTN_SEND)->EnableWindow(true);
	GetDlgItem(IDC_BTN_STOP)->EnableWindow(true);
}

void CMFCSocketDlg_Client::SocketSendMessage()
{
	OutputDebugString(_T("[Client Dlg]: send message"));
	UpdateData();
	/*
	userinfo uinf;
	strcpy(uinf.cUserName,m_sUserName);
	strcpy(uinf.csMsg,m_sMsg);

	char *buff=(char*)&uinf;
	m_Client.Send(buff,sizeof(userinfo));
	*/
	//CString s;
	//s.Format()
	
	//OutputDebugString(sMsg);

	//sprintf(szBuff, "%d %s", m_clientID, sMsg);
	//sprintf(szBuff, "%s", sMsg);
	//strcpy(szBuff, sMsg);
	char str[256];
	GetDlgItemTextA(this->GetSafeHwnd(),IDC_EDIT_MESSAGE,str,256);
	//char* buff = (char*)sMsg.GetBuffer(sMsg.GetLength());
	//strcpy(szBuff, "ppklitghjhsdf");
	sprintf(szBuff, "%d%d%s", DigitalCounter(m_clientID), m_clientID, str);
	//strcpy(szBuff, str);
	OutputDebugStringA(szBuff);
	int size = sizeof(szBuff);
	//OutputDebugString(Int2String(size));
	OutputDebugString(_T("---------------------"));
	m_socket.Send(szBuff, size);
}

void CMFCSocketDlg_Client::SocketStopConnected()
{
	OutputDebugString(_T("[Client Dlg]: stop connected"));
	/*
	m_Client.ShutDown(2);
	m_Client.Close();

	GetDlgItem(IDC_STOP)->EnableWindow(false);
	GetDlgItem(IDC_CONNECT)->EnableWindow(true);
	*/
	m_socket.ShutDown(2);
	m_socket.Close();

	GetDlgItem(IDC_BTN_CONNECT)->EnableWindow(true);
	GetDlgItem(IDC_BTN_SEND)->EnableWindow(false);
	GetDlgItem(IDC_BTN_STOP)->EnableWindow(false);
}
void CMFCSocketDlg_Client::OnBnClickedBtnConnect()
{
	SocketConnectServer();
}

void CMFCSocketDlg_Client::SocketReceiveMessage(char* message)
{
	OutputDebugString(_T("[Client Dlg]: receive message"));
	CString s(message);
	GetDlgItem(IDC_STATIC)->SetWindowText(s);
}

void CMFCSocketDlg_Client::OnBnClickedBtnSend()
{
	SocketSendMessage();
}

void CMFCSocketDlg_Client::OnBnClickedBtnStop()
{
	SocketStopConnected();
}

LRESULT CMFCSocketDlg_Client::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
	// TODO: Add your specialized code here and/or call the base class

	return CDialog::DefWindowProc(message, wParam, lParam);
}
